package org.jmq.myblog.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jmq.myblog.mapper.UserMapper;
import org.jmq.myblog.pojo.User;
import org.jmq.myblog.service.UserService;
import org.jmq.myblog.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {

    @Autowired(required = false)
    private UserMapper userMapper;

    //创建邮件发送服务类对象
    @Autowired(required = false)
    private JavaMailSender javaMailSender;

    @Override
    public ResponseResult sendCode(String userEmail, HttpSession session) {

        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("");
            message.setTo(userEmail);
            //设置标题
            message.setSubject("邮箱验证码:");
            Random rd = new Random();
            int code = rd.nextInt(10000);

            message.setText("你的邮箱验证码是:"+code);
            javaMailSender.send(message);
            session.setAttribute("code",code);
            return new ResponseResult(200,"发送成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(500,"发送失败");
        }
    }

    @Override
    public ResponseResult checkCode(String email,String code,String password,HttpSession session) {

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("useremail",email);
        User user = userMapper.selectOne(wrapper);
        if(user==null){
            return new ResponseResult(500,"用户不存在");
        }

        String scode = session.getAttribute("code").toString();
        if(scode.equals(code)){
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            user.setPassword(passwordEncoder.encode(password));
            int count = userMapper.updateById(user);
            if(count>0){
                return new ResponseResult(200,"success");
            }
            return new ResponseResult(500,"未知错误");
        }else {
            return new ResponseResult(500,"验证码错误");
        }
    }
}
